<?php

namespace lib\Server\Service;;
/**
 * 热加载文件
 */
class HotReloadService
{
	static public $files = [];
	static public $dir;
	static public $suffix;
	static public $server;

	public function __construct($server, $watchDir = null, $suffix = ['php'])
	{
		self::$suffix = $suffix;

		if (!is_dir($watchDir)) {
			$watchDir = ROOT_DIR;
		}
		self::$dir    = $watchDir;
		self::$server = $server;

		#初始化文件列表
		$this->ListFolder(true);
		#开始监听
		swoole_timer_tick(1000, [$this, 'watch']);
	}

	public function watch()
	{
		$this->ListFolder();
	}

	public function ListFolder($init = false)
	{
		$fileUpdata = false;
		foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(self::$dir), \RecursiveIteratorIterator::CHILD_FIRST) as $fileInfo) {
			if (
				($fileInfo->getFilename() == "." || $fileInfo->getFilename() == "..")
				|| (!in_array(fileSuffix(strtolower($fileInfo->getFilename())), self::$suffix)
				    && !in_array(fileSuffix(strtolower($fileInfo->getFilename())), self::$suffix))
			) {
				continue;
			}

			$fileNamePath = $fileInfo->getPath() . '/' . $fileInfo->getFilename();

			if ($init) {
				self::$files[$fileNamePath] = $fileInfo->getCTime();
			}
			else {
				if (!self::$files[$fileNamePath]) {
//					unlink(ROOT_DIR.DIRECTORY_SEPARATOR.'composer.lock');
					system('composer update');
					self::$files[$fileNamePath] = $fileInfo->getCTime();
					echo "[Add]" . $fileNamePath . PHP_EOL;
				}
				elseif ($fileInfo->getCTime() != self::$files[$fileNamePath]) {
					self::$files[$fileNamePath] = $fileInfo->getCTime();
					$fileUpdata[]               = $fileInfo->getFilename();
					echo "[Change]" . $fileNamePath . PHP_EOL;
				}
			}
		}

		if (!$init) {
			if ($fileUpdata) {
//				self::$server->reload();

				self::$server->reload();

			}
		}
	}
}